<template>
  <el-dialog :close-on-click-modal='false' v-drag :title="record.id?$t('编辑') : $t('添加')" :v-if="dialogVisible" :visible.sync="dialogVisible" width="800px" top="10vh" @close='close'>
    <div class="dialogContentBoxMaxHeight80">
      <el-form ref="form" :model="record" label-width="100px" :rules="rules" class="blackFileForm" label-position="left" style="margin:0 30px;">
        <el-form-item :label="$t('策略名称')" prop="name">
          <el-input v-emoji v-model="record.name" ref="name" style="width:400px;" size='small'></el-input>
        </el-form-item>
        <el-form-item :label="$t('描述')" prop="desc">
          <el-input v-emoji v-model="record.desc" ref="desc" style="width:400px;" :autosize="{ minRows: 4 }" size='small' type="textarea"></el-input>
        </el-form-item>

        <el-table ref="multipleTable" :data="record.rule_map" size='mini'>
          <el-table-column prop="class_type" align='center' :label="$t('开关')" min-width="100">
            <template slot-scope="scope">
              <el-switch :width="45" v-model="scope.row.switch" class="switchs switch" active-color="#009966" inactive-color="#CCCCCC" active-value="enable" inactive-value="disable" :active-text="$t('开')" :inactive-text="$t('关')">
              </el-switch>
            </template>
          </el-table-column>
          <el-table-column prop="class_name" align='center' :label="$t('协议名称')" min-width="100">
            <template slot-scope="scope">
              {{ scope.row.proto }}
            </template>
          </el-table-column>
          <el-table-column prop="dir" align="center" :label="$t('方向')" min-width="120">
            <template slot-scope="scope">
              <el-select v-model="scope.row.dir" :disabled='dirEditList.includes(scope.row.proto)' :ref="'dir' + (scope.$index + 1)" size='mini'>
                <el-option v-for="(value, key) in dirList" :key="key" :label="value" :value="key">
                </el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column prop="action" align="center" :label="$t('动作')" min-width="120">
            <template slot-scope="scope">
              <el-select v-model="scope.row.action" :ref="'action' + (scope.$index + 1)" size='mini'>
                <el-option v-for="(value, key) in actionList" :key="key" :label="value" :value="key">
                </el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column prop="type" align="center" :label="$t('文件类型')" width="150">
            <template slot-scope="scope">
              <el-button type="success" @click="typeDialogVisible(scope.row)" plain size="mini" :class="'setting' + (scope.$index + 1)">{{$t('配置/查看')}}</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
    </div>
    <blackFile-batch-dialog v-if="blackFileBatchDialogVisible" ref="refBlackFileBatchDialogVisible" @typeChange='typeChange'></blackFile-batch-dialog>
    <span slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submit" class="addSubmit">{{$t('确 定')}}</el-button>
      <el-button @click="close" class="addClose">{{$t('取 消')}}</el-button>
    </span>
  </el-dialog>
</template>
<script>
import { getBlackFileInfo, addBlacklistFile, editBlacklistFile } from '@/api/safe/black'
import BlackFileBatchDialog from './BlackFileBatchDialog.vue'
import typeArray from './typeArray'
import { inputClass, texttextClass, selectClass } from '@/utils/input-class.js'
export default {
  components: { BlackFileBatchDialog },
  name: 'BlackFileDialog',
  data () {
    var validateName = (rule, value, callback) => {
      if (!String(value).trim()) {
        callback(new Error(this.$t('请输入策略名称')))
      } else {
        callback()
      }
    }
    return {
      dialogVisible: false,
      blackFileBatchDialogVisible: false,
      typeAllList: typeArray,
      record: {
        desc: '',
        id: null,
        name: '',
        rule_map: [
          { action: 'alert', dir: 'upload', proto: 'http', switch: 'disable', type: '' },
          { action: 'alert', dir: 'upload', proto: 'ftp', switch: 'disable', type: '' },
          { action: 'alert', dir: 'upload', proto: 'smtp', switch: 'disable', type: '' },
          { action: 'alert', dir: 'download', proto: 'pop3', switch: 'disable', type: '' }
        ]
      },
      recordCopy: {
        desc: '',
        id: null,
        name: '',
        rule_map: [
          { action: 'alert', dir: 'upload', proto: 'http', switch: 'disable', type: '' },
          { action: 'alert', dir: 'upload', proto: 'ftp', switch: 'disable', type: '' },
          { action: 'alert', dir: 'upload', proto: 'smtp', switch: 'disable', type: '' },
          { action: 'alert', dir: 'download', proto: 'pop3', switch: 'disable', type: '' }
        ]
      },
      dirEditList: ['smtp', 'pop3'],
      typeList: [ //   alert/reject  告警/拒绝
        { value: 'alert', label: '告警' },
        { value: 'reject', label: '拒绝' }
      ],
      actionList: { 'alert': this.$t('告警'), 'deny': this.$t('阻断') },
      dirList: { 'upload': this.$t('上传'), 'download': this.$t('下载'), 'both': this.$t('双向') },
      rules: {
        name: [{ required: false, validator: validateName, trigger: 'blur' }]
      }
    }
  },
  watch: {
    'record.desc': {
      handler (newVal) {
        this.record.desc = newVal.replace(/[\r\n]/g, '')
      },
      immediate: true
    }
  },
  methods: {
    init (data) {
      this.dialogVisible = true
      this.$nextTick(() => {
        const data = ['name']
        const textdata = ['desc']
        inputClass(this.$refs, data)
        texttextClass(this.$refs, textdata)
        this.record.rule_map.forEach((item, index) => {
          const selectData = ['dir' + (index + 1), 'action' + (index + 1)]
          selectClass(this.$refs, selectData)
        })
      })
      if (data) {
        getBlackFileInfo({ name: data.name }).then(res => {
          this.record = Object.assign({}, res.info[0])
        })
      }
    },
    submit () {
      this.$refs.form.validate((valid) => {
        if (valid) {
          var formData = Object.assign({}, this.record)
          for (const index in formData.rule_map) {
            if (formData.rule_map[index]['typeList']) {
              delete formData.rule_map[index]['typeList']
            }
          }
          var flag = true
          for (var item of formData.rule_map) {
            if (item.switch === 'enable' && (!item.type || item.type === '500')) {
              flag = false
            }
          }
          if (flag) {
            formData.rule_map = JSON.stringify(formData.rule_map)
            if (this.record.id) {
              editBlacklistFile(formData).then(res => {
                if (res.status === 0) {
                  this.$message({
                    message: this.$t('编辑成功'),
                    type: 'success'
                  })
                  this.close()
                  this.$parent.listData()
                }
              })
            } else {
              addBlacklistFile(formData).then(res => {
                if (res.status === 0) {
                  this.$message({
                    message: this.$t('添加成功'),
                    type: 'success'
                  })
                  this.close()
                  this.$parent.listData()
                }
              })
            }
          } else {
            this.$messages.error(this.$t('协议开启后必须配置文件类型!'))
          }
        }
      })
    },
    // 批量配置按钮
    typeDialogVisible (data) {
      this.blackFileBatchDialogVisible = true
      this.$nextTick(() => {
        this.$refs.refBlackFileBatchDialogVisible.init(data, this.record)
      })
    },
    typeChange (name, data) {
      for (const index in this.record.rule_map) {
        if (this.record.rule_map[index].proto === name) {
          this.record.rule_map[index].typeList = data
          if (data.length === 0) {
            this.record.rule_map[index].type = '500'
          } else if (data.length < this.typeAllList.length) {
            this.record.rule_map[index].type = data[0].id
            for (let item in data) {
              if (item > 0) {
                this.record.rule_map[index].type += ',' + data[item].id
              }
            }
          } else if (data.length === this.typeAllList.length) {
            this.record.rule_map[index].type = '0'
          }
        }
      }
    },
    close () {
      this.dialogVisible = false
      this.record = JSON.parse(JSON.stringify(this.recordCopy))
      this.$refs.multipleTable.clearSelection()
      this.$refs.form.resetFields()
    }
  }
}
</script>
<style lang="less" scoped>
.el-switch {
  margin-left: 15px;
}
</style>
